/**
 * @attention 仅适用于dgm v2.0
 */

#include "drv_dgm.h"
#include "string.h"

/**
 * @brief 初始化一个dgm实例
 * @param dgm: dgm实例
 * @param id: 节点ID
 * @param hfdcan: fdcan句柄
 * @retval None
 */
void DGM_Init(Dgm_t *dgm, uint8_t id, FDCAN_HandleTypeDef *hfdcan)
{
    dgm->id = id;
    dgm->status = DGM_DISABLE;
    dgm->hfdcan = hfdcan;
}

/**
 * @brief 发送无数据的dgm指令
 * @param dgm: dgm实例
 * @param cmd: 指令
 * @retval None
 */
void DGM_SendCmdWithoutData(Dgm_t *dgm, DgmCmdIndex_t cmd)
{
    FDCAN_TxHeaderTypeDef txHeader = {0};
    txHeader.Identifier = (dgm->id << 6) | cmd;
    txHeader.IdType = FDCAN_STANDARD_ID;
    txHeader.TxFrameType = FDCAN_DATA_FRAME;
    txHeader.DataLength = FDCAN_DLC_BYTES_0;
    txHeader.ErrorStateIndicator = FDCAN_ESI_ACTIVE;
    txHeader.BitRateSwitch = FDCAN_BRS_OFF;
    txHeader.FDFormat = FDCAN_CLASSIC_CAN;
    txHeader.TxEventFifoControl = FDCAN_NO_TX_EVENTS;
    txHeader.MessageMarker = 0x00;

    if (HAL_FDCAN_GetTxFifoFreeLevel(dgm->hfdcan) > 0)
    {
        HAL_FDCAN_AddMessageToTxFifoQ(dgm->hfdcan, &txHeader, NULL);
    }
}

/**
 * @brief 发送float数据的dgm指令
 * @param dgm: dgm实例
 * @param cmd: 指令
 * @param data: 数据
 * @retval None
 */
void DGM_SendCmdWithFloat(Dgm_t *dgm, DgmCmdIndex_t cmd, float data)
{
    FDCAN_TxHeaderTypeDef txHeader = {0};
    txHeader.Identifier = (dgm->id << 6) | cmd;
    txHeader.IdType = FDCAN_STANDARD_ID;
    txHeader.TxFrameType = FDCAN_DATA_FRAME;
    txHeader.DataLength = FDCAN_DLC_BYTES_4;
    txHeader.ErrorStateIndicator = FDCAN_ESI_ACTIVE;
    txHeader.BitRateSwitch = FDCAN_BRS_OFF;
    txHeader.FDFormat = FDCAN_CLASSIC_CAN;
    txHeader.TxEventFifoControl = FDCAN_NO_TX_EVENTS;
    txHeader.MessageMarker = 0x00;

    uint8_t buf[4] = {0};
    memcpy(buf, &data, sizeof(data));

    if (HAL_FDCAN_GetTxFifoFreeLevel(dgm->hfdcan) > 0)
    {
        HAL_FDCAN_AddMessageToTxFifoQ(dgm->hfdcan, &txHeader, buf);
    }
}
